/*
 * Copyright (C) 2007 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package android.contest.alarmclock;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.contest.R;
import android.contest.constant.Constant;
import android.contest.ui.NotifyActivity;
import android.contest.ui.TaskListView;
import android.contest.util.Log;
import android.contest.weather.Weather;
import android.os.Bundle;

/**
 * Glue class: connects AlarmAlert IntentReceiver to AlarmAlert
 * activity.  Passes through Alarm ID.
 */
public class AlarmReceiver extends BroadcastReceiver {
	
    @Override
    public void onReceive(final Context context, Intent intent) {
    	Bundle b  = intent.getExtras();
    	int laundry_type = b.getInt(Constant.LAUNDRY_TYPE);
    	final long alarm_id = b.getLong(Constant.ALARM_ID);
    	final long alarm_time = b.getLong(Constant.ALARM_TIME);
    	final long alarm_time_nextstep = b.getLong(Constant.ALARM_TIME_NEXTSTEP);
    	
    	String currentPreferencesFileName = TaskListView.PREFIX_PREFERENCES_FILE_NAME + alarm_id;
    	SharedPreferences sharedPref = context.getSharedPreferences(currentPreferencesFileName, android.content.Context.MODE_PRIVATE);
    	String alarm_condition = context.getResources().getString(R.string.service_condition);
    	int alarm_condition_value = Integer.parseInt(sharedPref.getString(alarm_condition, "0"));
    	int level = alarm_condition_value % 2 + 1;
    	
    	// Notify the front end of the corresponding laundry action
//		Intent fireAlarm = new Intent(context, NotifyActivity.class);
//		fireAlarm.putExtra(Constant.LAUNDRY_TYPE, laundry_type);
//        fireAlarm.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION);
//        context.startActivity(fireAlarm);
        if(!Weather.SatisfyCondition(context, level)){
        	// TODO: schedule next according to the history
        }
        else{
        	/* Wake the device and stay awake until the AlarmAlert intent is
             * handled. */
            AlarmAlertWakeLock.acquire(context);
		Intent notifyIntent =  new Intent(context, NotifyActivity.class);
		notifyIntent.putExtra(NotifyActivity.EXTRA_ITEM, alarm_id);
		notifyIntent.putExtra(NotifyActivity.EXTRA_STEP, laundry_type);
		notifyIntent.putExtra(NotifyActivity.EXTRA_TIME, alarm_time);
		notifyIntent.putExtra(NotifyActivity.EXTRA_STEP_TIME, alarm_time_nextstep);
		//notifyIntent.putExtra(NotifyActivity.EXTRA_CHOICE, true);
		/*Only the first step of the item has the privilege to be cancelled*/
		switch(laundry_type){
		case Constant.WASH_CLOTHES:
			notifyIntent.putExtra(NotifyActivity.EXTRA_CHOICE, true);
			break;
		case Constant.DRY_CLOTHES:
			notifyIntent.putExtra(NotifyActivity.EXTRA_CHOICE, false);
			break;
		case Constant.COLLECT_CLOTHES:
			notifyIntent.putExtra(NotifyActivity.EXTRA_CHOICE, false);
			break;
		}
		notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
		context.startActivity(notifyIntent);
		
		
		
        if(Log.LOGV){
    	switch (laundry_type){
	    	case Constant.WASH_CLOTHES:
        		Log.v(Log.LOGALARM, "AlarmReceiver:onReceiver() receives WASH_CLOTHES");
//	    		if(!Weather.SatisfyCondition(context)){
//	        		Log.v(Log.LOGALARM, "AlarmReceiver:onReceiver() weather does not satisfy!! cancel current epoch and return");
//	        		AlarmDBMgr.getMgrInstance(context).cancelCurrentEpoch(alarm_id);
//	        		AlarmMgr.setNextAlert(context);
//	        		return;
////	    		}
//        		Intent notifyIntent =  new Intent(context, NotifyActivity.class);
//        		notifyIntent.putExtra(NotifyActivity.EXTRA_ITEM, alarm_id);
//        		notifyIntent.putExtra(NotifyActivity.EXTRA_STEP, laundry_type);
//        		notifyIntent.putExtra(NotifyActivity.EXTRA_CHOICE, true);
//        		notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//        		context.startActivity(notifyIntent);
//        		NotifyActivity.notifyLaundry(context, alarm_id, laundry_type, true, 
//        			new OnClickListener() {
//						public void onClick(DialogInterface dialog, int which) {
//							//do nothing
//						}
//					},
//					new OnClickListener() {
//						public void onClick(DialogInterface dialog, int which) {
//							AlarmDBMgr adbm = AlarmDBMgr.getMgrInstance(context);
//			        		Log.v(Log.LOGALARM, "AlarmReceiver:onReceiver() before cancelCurrentEpoch");
//							adbm.dump();
//							adbm.cancelCurrentEpoch(alarm_id);
//			        		Log.v(Log.LOGALARM, "AlarmReceiver:onReceiver() after cancelCurrentEpoch");
//							adbm.dump();
//					    	AlarmMgr.setNextAlert(context);
//						}
//					}, 
//					new OnCancelListener() {
//
//						public void onCancel(DialogInterface arg0) {
//							// TODO Auto-generated method stub
//							
//						}}); 
//        		Intent notifyIntent =  new Intent(context, AlarmAlert.class);
//        		notifyIntent.putExtra(NotifyActivity.EXTRA_ITEM, alarm_id);
//        		notifyIntent.putExtra(NotifyActivity.EXTRA_STEP, laundry_type);
//        		notifyIntent.putExtra(NotifyActivity.EXTRA_CHOICE, true);
//        		notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_EXCLUDE_FROM_RECENTS);
//        		context.startActivity(notifyIntent);
	    		break;
	    	case Constant.DRY_CLOTHES:
        		Log.v(Log.LOGALARM, "AlarmReceiver:onReceiver() receives DRY_CLOTHES");
//        		NotifyActivity.notifyLaundry(context, alarm_id, laundry_type, false, 
//            			new OnClickListener() {
//    						public void onClick(DialogInterface dialog, int which) {
//    							//do nothing
//    						}
//    					},null, new OnCancelListener() {
//
//						public void onCancel(DialogInterface arg0) {
//							// TODO Auto-generated method stub
//							
//						}}
//    				); 
	            break;
	    	case Constant.COLLECT_CLOTHES:
        		Log.v(Log.LOGALARM, "AlarmReceiver:onReceiver() receives COLLECT_CLOTHES");
//        		NotifyActivity.notifyLaundry(context, alarm_id, laundry_type, false, 
//            			new OnClickListener() {
//    						public void onClick(DialogInterface dialog, int which) {
//    							//do nothing
//    						}
//    					},null, new OnCancelListener() {
//
//    						public void onCancel(DialogInterface arg0) {
//    							// TODO Auto-generated method stub
//    							
//    						}}
//    				);
	    		break;
	    		default:
	    			Log.e(Log.LOGALARM, "AlarmReceiver: unexpected laundry_type");
	    	}
        }
        this.releaseLocks();
        }
        
        
    	this.alertHandler(context, alarm_id, laundry_type);
    	
    }
    
    private synchronized void releaseLocks() {
        AlarmAlertWakeLock.release();
    }
    
    /**
     * 1. Delete this item from the <b>alarmScheduledTable</b> </br>
     * 2. if the type of current alert is <b>wash</b>, 
     * then schedule the next <b>(wash, dry, collect)</b> events</br>
     * 3. Pick the latest alarm in the <b>alarmScheduledTable</b>, report it to the OS </br>
     * @param context 
     * @param laundry_type 
     * @param alarm_id 
     */
    private void alertHandler(Context context, long alarm_id, int laundry_type){
    	
//    	AlarmDBMgr adbm = AlarmDBMgr.getMgrInstance(context);
    	//here needn't to delete the alert time. the setNextAlert() will handle it
//    	boolean successflag = adbm.deleteAlertedAlarm(alarm_id, laundry_type); 
//    	if(Log.LOGV )
//    		Log.v(Log.LOGALARM, "AlarmReceiver:alartHandler() delete alerted alarm successfully!");
//		/*There is no need to do schedule Next Epoch because setNextAlert will arrange the pool!*/    	
//    	if(laundry_type == Constant.WASH_CLOTHES){
//    		adbm.scheduleNextEpoch(alarm_id);
//    	}
    	
    	AlarmMgr.setNextAlert(context);
    }
}
